import React, { useState, useEffect } from 'react';
import {
  Form,
  Button,
  Space,
  Input,
  notification,
  Select,
  Tooltip,
} from 'antd';
import { componentsMap } from '@/utils/util';
import {
  ContactsFilled,
  PlusOutlined,
  MinusCircleOutlined,
} from '@ant-design/icons';
import { useModel } from 'umi';
import API from '@/api/xjindex.js';
import moment from 'moment';
const { Option } = Select;
// initList 有值  modify  true禁用，不可修改   点编辑后false启用，编辑状态
//          无值  modify  false启用 新增状态
//

//  3编辑   2 新增   1查看
const operationManageEdit = ({ initList, menus }) => {
  const { initialState } = useModel('@@initialState');
  const { orgId, username, orgName } = initialState.info;
  const [form] = Form.useForm();
  const [province] = useState([]);
  const [city, setCity] = useState([]);
  const [district, setDistrict] = useState([]);
  const [personList, setPersonList] = useState([]);
  const [modify, setModify] = useState(null);
  const [modifyList, setModifyList] = useState({
    state: menus.state,
    id: initList.id,
  });

  function getCity(value) {
    API.getAllCity({ areaNo: value }).then((res) => {
      if (res) {
        setCity(
          res.t.map((item) => {
            return {
              label: item.areaName,
              value: item.areaNo,
            };
          }),
        );
      }
    });
  }
  function getDistrict(value) {
    const values = form.getFieldsValue();
    values.district = null;
    form.setFieldsValue(values);
    API.getAllDistrict({ areaNo: value }).then((res) => {
      if (res) {
        setDistrict(
          res.t.map((item) => {
            return {
              label: item.areaName,
              value: item.areaNo,
            };
          }),
        );
      }
    });
  }
  const TableList = [
    {
      label: '单位名称',
      name: 'orgName',
      type: 'input',
      otherProps: {
        disabled: true,
      },
    },
    {
      label: '统一社会信用代码',
      name: 'socialcreditCodes',
      type: 'input',
      otherProps: {
        disabled: modifyList.state === 2 ? false : true,
      },
      rules: [
        {
          required: true,
          message: '请输入统一社会信用代码',
        },
        {
          //   pattern: /^[0-9A-Z]{18}$/,
          pattern: /^(?![0-9]+$)(?![A-Z]+$)[0-9A-Z]{18,18}$/, //后端说不按照网上的正确格式,按他们提供的格式
          message:
            '统一社会信用代码的格式不正确 , 需要18位数字+大写英文字母的组合',
        },
      ],
    },
    {
      label: '所属区域',
      type: 'select',
      isremark: true,
      children: [
        {
          type: 'select',
          name: 'province',
          otherProps: {
            options: province,
            onChange: getCity,
          },
        },
        {
          type: 'select',
          name: 'city',
          otherProps: {
            options: city,
            onChange: getDistrict,
          },
          rules: [
            {
              required: true,
              message: '请选择所属区域的市',
            },
          ],
        },
        {
          type: 'select',
          name: 'district',
          otherProps: {
            options: district,
          },
          rules: [
            {
              required: true,
              message: '请选择所属区域的区/县',
            },
          ],
        },
      ],
    },
    {
      label: '详细地址',
      name: 'address',
      type: 'input',
      isremark: true,
      rules: [
        {
          required: true,
          message: '请输入详细地址',
        },
      ],
      otherProps: {
        disabled: modify,
      },
    },
    {
      label: '创建人',
      name: 'createName',
      type: 'input',
      otherProps: {
        disabled: true,
      },
    },
    {
      label: '创建时间',
      name: 'createDate',
      type: 'input',
      otherProps: {
        disabled: true,
      },
    },
  ];
  const TableList1 = [
    {
      label: '网络安全部门',
      name: 'responsibleDepartmentName',
      type: 'input',
      rules: [
        {
          required: true,
          message: '请输入网络安全部门',
        },
      ],
      otherProps: {
        disabled: modify,
      },
    },
  ];
  const editSubmitFun = (values) => {
    const params = {
      id: modifyList.id || initList.id,
      district: values.district,
      city: values.city,
      address: values.address.replace(/\s+/g, ''),
      socialcreditCodes: values.socialcreditCodes,
      cyberSecurityTeamList: [],
    };
    if (values.addemery) {
      values.addemery.forEach((element) => {
        if (element.userId) {
          element.flag = 3;
          element.responsibleDepartmentName =
            values.responsibleDepartmentName.replace(/\s+/g, '');
          params.cyberSecurityTeamList.push(element);
        }
      });
    }
    values.first[0].flag = 1;
    values.direct[0].flag = 2;
    values.first[0].responsibleDepartmentName =
      values.responsibleDepartmentName.replace(/\s+/g, '');
    values.direct[0].responsibleDepartmentName =
      values.responsibleDepartmentName.replace(/\s+/g, '');
    params.cyberSecurityTeamList.push(values.first[0]);
    params.cyberSecurityTeamList.push(values.direct[0]);
    API.modUnitManagementById(params).then((res) => {
      if (res) {
        notification.success({
          message: '修改成功',
        });
        setModify(true);
      }
    });
  };
  const createSubmitFun = (values) => {
    const params = {
      orgId: menus.key,
      district: values.district,
      city: values.city,
      address: values.address.replace(/\s+/g, ''),
      socialcreditCodes: values.socialcreditCodes,
      cyberSecurityTeamList: [],
    };
    if (values.addemery) {
      values.addemery.forEach((element) => {
        if (element.userId) {
          element.flag = 3;
          element.responsibleDepartmentName =
            values.responsibleDepartmentName.replace(/\s+/g, '');
          params.cyberSecurityTeamList.push(element);
        }
      });
    }
    values.first[0].flag = 1;
    values.direct[0].flag = 2;
    values.first[0].responsibleDepartmentName =
      values.responsibleDepartmentName.replace(/\s+/g, '');
    values.direct[0].responsibleDepartmentName =
      values.responsibleDepartmentName.replace(/\s+/g, '');
    params.cyberSecurityTeamList.push(values.first[0]);
    params.cyberSecurityTeamList.push(values.direct[0]);
    API.addUnitManagement(params).then((res) => {
      if (res) {
        notification.success({
          message: '新增成功',
        });
        setModify(true);
        setModifyList({ ...modifyList, id: res.t });
      }
    });
  };
  const getPerson = () => {
    console.log(menus);
    API.selectPersonList({ id: menus.key }).then((res) => {
      if (res) {
        setPersonList(res.t);
      }
    });
  };
  function editInit() {
    getCity(320000);
    getDistrict(initList.city);
    const first = [];
    const direct = [];
    const emery = [];
    initList.cyberSecurityTeamList &&
      initList.cyberSecurityTeamList.map((item) => {
        if (item.userId) {
          if (item.flag == 1) {
            first.push(item);
            initList.responsibleDepartmentName = item.responsibleDepartmentName;
          } else if (item.flag == 2) {
            direct.push(item);
          } else if (item.flag == 3) {
            emery.push(item);
          }
        }
      });
    form.setFieldsValue({
      ...initList,
      first: first,
      direct: direct,
      addemery: emery,
      province: '江苏省',
      city: +initList.city,
      district: +initList.district,
    });
  }
  function createInit() {
    API.getAllProvince().then((res) => {
      if (res) {
        form.setFieldsValue({
          createName: username,
          createDate: moment().format('YYYY-MM-DD'),
          orgName: orgName,
          addemery: [],
          first: [{}],
          direct: [{}],
          province: '江苏省',
          city: null,
          district: null,
          socialcreditCodes: '',
          address: '',
          responsibleDepartmentName: '',
        });
      }
    });
    getCity(320000);
    setModifyList({ ...modifyList, state: 3 });
  }
  const init = () => {
    getPerson();
    if (menus.state === 1) {
      editInit();
      setModify(true);
      setModifyList({ ...modifyList, state: 1 });
    } else if (menus.state === 2) {
      createInit();
      setModify(false);
      setModifyList({ ...modifyList, state: 2 });
    }
  };
  const searchPhone = (v) => {
    const result = personList.filter((item) => {
      return item.id == v;
    });
    return result[0];
  };
  const PhoneListFirst = (index, value) => {
    const values = form.getFieldsValue();
    values.first[index].mobilePhone = searchPhone(value).phone;
    form.setFieldsValue(values);
  };
  const PhoneListDirect = (index, value) => {
    const values = form.getFieldsValue();
    values.direct[index].mobilePhone = searchPhone(value).phone;
    form.setFieldsValue(values);
  };
  const PhoneListEmery = (index, value) => {
    const values = form.getFieldsValue();
    values.addemery[index].mobilePhone = searchPhone(value).phone;
    form.setFieldsValue(values);
  };
  useEffect(() => {
    init();
  }, [menus.state]);
  return (
    <div className="main-x">
      <Form
        form={form}
        onFinish={modifyList.state === 3 ? editSubmitFun : createSubmitFun}
      >
        <div className="bread-y bgf">
          {/* 当状态为2时，新增 单位显示自己的单位，如果不是新增的话就显示传过来的单位 */}
          <div className="title-y">
            {modifyList.state === 2 ? orgName : initList.orgName}
          </div>
          {(modifyList.state !== 2 && orgId === initList.orgId) ||
          modifyList.state === 2 ? (
            <div>
              {modifyList.state === 2 ? null : (
                <Button
                  disabled={!modify}
                  type="primary"
                  onClick={() => {
                    setModify(false),
                      setModifyList({ ...modifyList, state: 3 });
                  }}
                >
                  编辑
                </Button>
              )}
              <Button
                disabled={modify}
                type="primary"
                htmlType="submit"
                className="ml10"
              >
                保存
              </Button>
              {modifyList.state === 3 ? (
                <Button
                  className="ml10"
                  type="primary"
                  onClick={() => {
                    editInit();
                    setModify(true);
                  }}
                  disabled={modify}
                >
                  取消
                </Button>
              ) : null}
            </div>
          ) : null}
        </div>
        <div className="base-title">单位信息</div>
        <div className="ant-form-inline form-x max-z bgf">
          {TableList.map((item) => {
            return (
              <Form.Item
                key={item.label}
                label={item.label}
                name={item.name}
                disabled={item.disabled}
                className={item.isremark ? 'block max-only' : 'max-only'}
                rules={item.rules}
              >
                {item.children
                  ? item.children.map((item) => {
                      return (
                        <Form.Item
                          key={item.name}
                          name={item.name}
                          rules={item.rules}
                          style={{ marginBottom: '0px' }}
                        >
                          {componentsMap(item.type, item.otherProps, modify)}
                        </Form.Item>
                      );
                    })
                  : componentsMap(item.type, item.otherProps, modify)}
              </Form.Item>
            );
          })}
        </div>
        <div className="base-title mt20">网络安全责任小组</div>
        <div className="ant-form-inline form-x bgf max-z">
          {TableList1.map((item) => {
            return (
              <Form.Item
                key={item.name}
                label={item.label}
                name={item.name}
                disabled={item.disabled}
                rules={item.rules}
                className={item.isremark ? 'block' : ''}
              >
                {componentsMap(item.type, item.otherProps, modify)}
              </Form.Item>
            );
          })}
          <Form.Item className="block">
            <Button type="link">
              <ContactsFilled />
              网络安全责任人
            </Button>
          </Form.Item>
          <Form.List name="first">
            {(fields, {}) => (
              <>
                {fields.map(({ name, key, ...restField }, index) => (
                  <Space key={key} align="baseline">
                    <Form.Item
                      {...restField}
                      label="姓名"
                      name={[name, 'userId']}
                      rules={[
                        { required: true, message: '请选择网络安全责任人' },
                      ]}
                    >
                      <Select
                        disabled={modify}
                        placeholder="请选择"
                        placement="topRight"
                        onChange={(value) => PhoneListFirst(index, value)}
                      >
                        {personList.map((item) => {
                          return <Option value={item.id}>{item.name}</Option>;
                        })}
                      </Select>
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      label="职务"
                      name={[name, 'job']}
                      rules={[
                        {
                          required: true,
                          message: '请输入网络安全责任人的职务',
                        },
                      ]}
                      getValueFromEvent={(event) =>
                        event.target.value.replace(/\s+/g, '')
                      }
                    >
                      <Input disabled={modify} placeholder="请输入"></Input>
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      label="移动电话"
                      name={[name, 'mobilePhone']}
                    >
                      <Input disabled></Input>
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      label="办公电话"
                      name={[name, 'officePhone']}
                    >
                      <Input disabled={modify} placeholder="请输入"></Input>
                    </Form.Item>
                  </Space>
                ))}
              </>
            )}
          </Form.List>
          <Form.Item className="block">
            <Button type="link">
              <ContactsFilled />
              直接责任人
            </Button>
          </Form.Item>
          <Form.List name="direct">
            {(fields, {}) => (
              <>
                {fields.map(({ name, key, ...restField }, index) => (
                  <Space key={key} align="baseline">
                    <Form.Item
                      {...restField}
                      label="姓名"
                      name={[name, 'userId']}
                      rules={[{ required: true, message: '请选择直接责任人' }]}
                    >
                      <Select
                        disabled={modify}
                        placeholder="请选择"
                        placement="topRight"
                        onChange={(value) => {
                          PhoneListDirect(index, value);
                        }}
                      >
                        {personList.map((item) => {
                          return <Option value={item.id}>{item.name}</Option>;
                        })}
                      </Select>
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      label="职务"
                      name={[name, 'job']}
                      rules={[
                        { required: true, message: '请输入直接责任人的职务' },
                      ]}
                      getValueFromEvent={(event) =>
                        event.target.value.replace(/\s+/g, '')
                      }
                    >
                      <Input disabled={modify} placeholder="请输入"></Input>
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      label="移动电话"
                      name={[name, 'mobilePhone']}
                    >
                      <Input disabled></Input>
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      label="办公电话"
                      name={[name, 'officePhone']}
                    >
                      <Input disabled={modify} placeholder="请输入"></Input>
                    </Form.Item>
                  </Space>
                ))}
              </>
            )}
          </Form.List>
          <Form.Item className="block">
            <Tooltip
              placement="right"
              title="无信息：未添加应急联系人"
              color="#2db7f5"
            >
              <Button type="link">
                <ContactsFilled />
                应急联系人
              </Button>
            </Tooltip>
          </Form.Item>
          <Form.List name="addemery">
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ name, key, ...restField }, index) => (
                  <Space key={key} align="baseline">
                    <Form.Item
                      {...restField}
                      label="姓名"
                      name={[name, 'userId']}
                      rules={[{ required: true, message: '请选择应急联系人' }]}
                    >
                      <Select
                        disabled={modify}
                        placeholder="请选择"
                        placement="topRight"
                        onChange={(value) => PhoneListEmery(index, value)}
                      >
                        {personList.map((item) => {
                          return <Option value={item.id}>{item.name}</Option>;
                        })}
                      </Select>
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      label="职务"
                      name={[name, 'job']}
                      rules={[
                        { required: true, message: '请输入应急联系人的职务' },
                      ]}
                      getValueFromEvent={(event) =>
                        event.target.value.replace(/\s+/g, '')
                      }
                    >
                      <Input disabled={modify} placeholder="请输入"></Input>
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      label="移动电话"
                      name={[name, 'mobilePhone']}
                    >
                      <Input disabled></Input>
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      label="办公电话"
                      name={[name, 'officePhone']}
                    >
                      <Input disabled={modify} placeholder="请输入"></Input>
                    </Form.Item>
                    <MinusCircleOutlined onClick={() => remove(name)} />
                  </Space>
                ))}
                {modify ? null : (
                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={() => add()}
                      block
                      icon={<PlusOutlined />}
                    >
                      添加应急联系人
                    </Button>
                  </Form.Item>
                )}
              </>
            )}
          </Form.List>
        </div>
      </Form>
    </div>
  );
};

export default operationManageEdit;
